package com.hyq.learn.ai.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;

/**
 * @author heyuqin
 * @date 2025/11/4 11:34
 */
public class RequestResponseCachingFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestResponseCachingFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        CachedRequestWrapper cachingRequestWrapper = new CachedRequestWrapper((HttpServletRequest) request);
        String requestUri = cachingRequestWrapper.getRequestURI();
        LOGGER.info("requestMethod: {}, requestUri: {}, requestBody: {}", cachingRequestWrapper.getMethod(), requestUri, cachingRequestWrapper.getCachedBody());
        if (!requestUri.startsWith("/mcp") && !requestUri.startsWith("/sse")) {
            ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
            chain.doFilter(cachingRequestWrapper, cachingResponseWrapper);
            cachingResponseWrapper.copyBodyToResponse();
        } else {
            chain.doFilter(cachingRequestWrapper, new LoggingSseResponseWrapper((HttpServletResponse) response));
        }
    }
}
